package com.qlogic.commons.platform.impls.lucene.handler;

import java.io.IOException;
import java.io.InputStream;

import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

public class JavaBuiltInRTFHandler implements ContentHandler {

	public String getText (InputStream is, String encoding) throws ContentHandlerException {
		String bodyText = null;

		DefaultStyledDocument styledDoc = new DefaultStyledDocument();
		try {
			new RTFEditorKit().read(is, styledDoc, 0);
			bodyText = styledDoc.getText(0, styledDoc.getLength());
		} catch (IOException e) {
			throw new ContentHandlerException(
					"Cannot extract text from a RTF document", e);
		} catch (BadLocationException e) {
			throw new ContentHandlerException(
					"Cannot extract text from a RTF document", e);
		}
		
		if (bodyText == null || bodyText.trim ().equals ("")) {
			return null;
		}

		return bodyText;
	}

	public Document getDocument(InputStream is, String encoding) throws ContentHandlerException {
		String bodyText = getText (is, encoding);
		if (bodyText != null) {
			Document doc = new Document();
			doc.add(new Field (BODY, bodyText, Field.Store.NO, Field.Index.TOKENIZED));
			return doc;
		}
		return null;
	}

}
